﻿using System.Data;

namespace DataServer.ApplicationLib.Rules
{
    public abstract class ConfigDataRuleBase : IConfigDataRule
    {

        public ConfigDataRuleBase(RuleContext ruleContext)
        {
            RuleContext = ruleContext;
        }

        public RuleContext RuleContext { get; }

        public ConfigDataRuleBase? Successor { get; set; }

        public void SetSuccessor(ConfigDataRuleBase configDataRuleBase)
        {
            if (Successor != null)
            {
                Successor.SetSuccessor(configDataRuleBase);
            }
            else
            {
                Successor = configDataRuleBase;
            }
        }

        protected VerifyRuleResult RunByRuleType(RuleType ruleType, bool breakAtOnce = true)
        {
            return RunByRuleType(RuleContext.TargetData, ruleType, breakAtOnce);
        }

        protected VerifyRuleResult RunByRuleType(DataTable targetData, RuleType ruleType, bool breakAtOnce)
        {
            var messages = new List<string>();
            if (RuleContext.ConfigRuleInfos != null && RuleContext.ConfigRuleInfos.Any())
            {
                foreach (var item in RuleContext.ConfigRuleInfos)
                {
                    if (!string.IsNullOrEmpty(item.RuleContent))
                    {
                        var result = item.ParaseRuleVerify(item.CheckWay)?.Verify(RuleContext);
                        if (result != null && !result.IsValid && !string.IsNullOrEmpty(result.Message))
                        {
                            messages.Add(result.Message);
                            if (item.CheckWay == DataCheckWay.InDB)
                            {
                                RuleContext.DbUpdatedColList?.Add(VerifyResultColumns.IsValid);
                            }
                            else
                            {
                                RuleContext.MemoryUpdatedColList?.Add(VerifyResultColumns.IsValid);
                            }

                            if (breakAtOnce)
                                break;
                        }
                    }
                }
            }
            return new VerifyRuleResult
            {
                IsValid = messages.Count == 0,
                Message = string.Join(',', messages)
            };
        }

        public abstract Task<VerifyRuleResult> VerifyData();
    }
}
